package com.zaker.touchtv.modules.live;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;

import com.zaker.touchtv.data.AppApiClient;
import com.zaker.touchtv.db.LiveDBHelper;
import com.zaker.touchtv.utils.Constants;
import com.zaker.touchtv.utils.TestDataUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.zaker.touchtv.utils.Constants.LOG_TAG;

public class LiveHeartbeatRunnable implements Runnable {

  private final Context mAppContext;

  private final String mLiveId;

  private Callback<Void> mHeartbeatRequestCallback;

  @Constants.LiveState
  private int mLiveState = Constants.LIVE_STARTING_STATE;

  private int beatCount = 0;

  public LiveHeartbeatRunnable(@NonNull Context appContext, @NonNull String liveId) {
    mAppContext = appContext;
    mLiveId = liveId;
  }

  @Override
  public void run() {
    String[] userInfo = LiveDBHelper.getUserInfo(mAppContext);
    if (userInfo[0] != null) {
      final Call<Void> stateCall = AppApiClient.getLiveService()
          .sendClientLiveState(TestDataUtils.PING_CLIENT_STATE_URL,
              userInfo[1],
              userInfo[2],
              mLiveId,
              mLiveState);
      stateCall.enqueue(new Callback<Void>() {
        @Override
        public void onResponse(Call<Void> call, Response<Void> response) {
          Log.i(LOG_TAG, " onResponse :" + response.code());
          if (mHeartbeatRequestCallback != null) {
            mHeartbeatRequestCallback.onResponse(call, response);
          }
        }

        @Override
        public void onFailure(Call<Void> call, Throwable t) {
          Log.i(LOG_TAG, " onFailure :" + t.getMessage());
          if (mHeartbeatRequestCallback != null) {
            mHeartbeatRequestCallback.onFailure(call, t);
          }
        }
      });
    }
    Log.i(LOG_TAG, (beatCount++) + " -- PollTask currentTimeMillis: "
        + (System.currentTimeMillis()));
  }

  public void setHeartbeatRequestCallback(Callback<Void> heartbeatRequestCallback) {
    this.mHeartbeatRequestCallback = heartbeatRequestCallback;
  }

  public void setLiveState(int liveState) {
    this.mLiveState = liveState;
  }
}
